package com.lhh.controller;


import com.lhh.core.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class UploadController {
    //文件上传的路径
    private static final String UPLOAD_FOLDER = "F:\\temp";
    //允许的文件类型格式
    private static final String[] ALLOWED_EXTENSIONS = {"jar"};


    /**
     * 文件上传*/
    @CrossOrigin
    @GetMapping(value = "/model")
    public String index() { return "file";}
    @CrossOrigin
    @ApiOperation(value = "文件上传",notes = "文件上传")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result FileUpload(@RequestParam("File") MultipartFile File) throws IOException {
        String extension = getExtension(File);
        if(File.isEmpty()) {
            return Result.fail("文件为空，请选择你的文件上传");
        }
        if(!isValidExtension(extension)) {
            return Result.fail("文件格式不正确");
        }
        SaveFile(File);
        return Result.success("文件" + File.getOriginalFilename() + "上传成功",1);
    }
    private void SaveFile(MultipartFile File) throws IOException {
        Path path = Paths.get(UPLOAD_FOLDER + "\\" + File.getOriginalFilename());
        File.transferTo(path);
    }

    /**
     * 获取文件的扩展名
     */
    private String getExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
    }



    /**
     * 验证文件类型是否正确
     */
    private boolean isValidExtension(String extension) {
        for(String allowedExtension : ALLOWED_EXTENSIONS) {
            if(extension.equalsIgnoreCase(allowedExtension)){
                return true;
            }
        }
        return false;
    }

}
